package com.example.forumsystem.services.impl;

import com.example.forumsystem.common.AppResult;
import com.example.forumsystem.common.ResultCode;
import com.example.forumsystem.dao.ArticleMapper;
import com.example.forumsystem.exception.ApplicationException;
import com.example.forumsystem.model.Article;
import com.example.forumsystem.model.Board;
import com.example.forumsystem.model.User;
import com.example.forumsystem.services.IArticleService;
import com.example.forumsystem.services.IBoardService;
import com.example.forumsystem.services.IUserService;
import com.example.forumsystem.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


@Slf4j
@Service
public class ArticleServiceImpi implements IArticleService {

    @Resource
    ArticleMapper articleMapper;

    @Resource
    IBoardService boardService;
    @Resource
    IUserService userService;
    /**
     * 新增文章
     * @param article 文章信息
     */
    @Override
    public void creaete(Article article) {
        // 参数校验
        if(article == null || article.getBoardId() == null
                || StringUtil.isEmpty(article.getTitle())
                || StringUtil.isEmpty(article.getContent())
                || article.getUserId() <= 0) {
            // 打印日志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 构建文章信息
        article.setVisitCount(0);           // 访问量
        article.setLikeCount((byte) 0);     // 点赞数
        article.setState((byte) 0);         // 是否被删除
        article.setReplyCount(0);           // 回复量
        // 初始化时间
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);
        // 写入数据库
        int row = articleMapper.insertSelective(article);

        /**
         * 此处的用户和文章需要单独查询,是因为防止前端传低无效的板块id和用户id
         */
        //获取用户信息
        User user = userService.selectById(article.getUserId());
        if(user == null || user.getId() <= 0) {
            // 打印日志
            log.info(ResultCode.FAILED_CREATE.toString() + "发帖失败 uerId: " + user);
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        // 更新用户文章数量
        userService.addOneArticleCountById(user.getId());

        Board board = boardService.selectById(article.getBoardId());
        if(board == null || board.getId() <= 0) {
            // 打印日志
            log.info(ResultCode.FAILED_CREATE.toString() + "发帖失败 uerId: " + user);
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        // 更新板块文章数量
        boardService.addOneArticleCountById(board.getId());

        if(row != 1) {
            // 打印日志
            log.info(ResultCode.FAILED_ARTICLE_FAILED_UPDATE.toString() + " row: " + row);
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_FAILED_UPDATE));
        }

        log.info("新增文章成功, " + article);
    }

    @Override
    public List<Article> selectAll() {

        List<Article> articles = articleMapper.selectAll();

        return articles;
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        // 校验参数合法性
        if (boardId == null || boardId <= 0) {
            // 打印日志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString() + " boardId: " + boardId);
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 根据板块id 获取板块
        Board board = boardService.selectById(boardId);

        // 校验板块是否存在
        if (board == null || board.getId() <= 0) {
            // 打印日志
            log.info(ResultCode.FAILED_BOARD_NOT_EXISTS.toString() + " boardId: " + boardId);
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }

        // 根据板块id获取帖子列表
        List<Article> articles = articleMapper.selectAllByBoardId(boardId);

        return articles;
    }

    @Override
    public Article selectDetailById(Long id) {

        if(id == null || id <= 0) {
            // 打印日志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 调用 DAO 获取文章详情
        Article article = articleMapper.selectDetailById(id);

        // 参数校验
        if(article == null) {
            // 打印日志
            log.info(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        // 构建一个更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId()); // 文章id
        updateArticle.setVisitCount(article.getVisitCount() + 1); // 文章访问量

        // 调用Service,更新文章访问数量
        articleMapper.updateByPrimaryKeySelective(updateArticle);

        // 修改返回文章的访问量
        article.setVisitCount(article.getVisitCount() + 1);

        // 返回
        return article;
    }

    @Override
    public void modify(Long id, String title, String content) {
        // 参数校验
        if(id == null || id <= 0 || StringUtil.isEmpty(title) || StringUtil.isEmpty(content)) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE_FAILED_UPDATE.toString());
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE_FAILED_UPDATE));
        }
        // 构建要修改的文章对象
        Article updateArticle = new Article();
        updateArticle.setId(id); // id
        updateArticle.setTitle(title); // 标题
        updateArticle.setContent(content); // 正文
        updateArticle.setUpdateTime(new Date()); // 更新时间
        // 调用 DAO 修改文章
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);

        if (row != 1) {
            // 打印日志
            log.info(ResultCode.FAILED_ARTICLE_UPDATE.toString());
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_UPDATE));
        }
    }

    @Override
    public Article selectById(Long id) {
        // 参数校验
        if(id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE_FAILED_UPDATE.toString());
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE_FAILED_UPDATE));
        }
        // 调用DAO获取文章
        Article article = articleMapper.selectByPrimaryKey(id);
        return article;
    }

    @Override
    public void thumbsUpById(Long id) {
        // 参数校验
        if(id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE_FAILED_UPDATE.toString());
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE_FAILED_UPDATE));
        }

        // 获取文章对象, 用来校验文章是否存在
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article == null || article.getState() == 1 || article.getDeleteState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        // 构建修改的文章对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setLikeCount((byte) (article.getLikeCount() + 1));
        updateArticle.setUpdateTime(new Date());


        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        // 参数校验
        if(id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE_FAILED_UPDATE.toString());
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE_FAILED_UPDATE));
        }

        // 根据文章id获取文章
        Article article = articleMapper.selectByPrimaryKey(id);
        // 校验文章状态
        if(article.getState() == 1 || article.getDeleteState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }

        // 构建修改文章对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setDeleteState((byte) 1);
        updateArticle.setUpdateTime(new Date());

        // 删除文章
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        // 校验是删除成功
        if(row != 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_DELETE.toString());
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_DELETE));
        }

        // 用户文章数-1
        userService.subOneArticleCountById(article.getUserId());
        // 板块文章数-1
        boardService.subOneArticleCountById(article.getBoardId());


    }

    @Override
    public void addOneReplyCountById(Long id) {
        // 参数校验
        if(id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE_FAILED_UPDATE.toString());
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE_FAILED_UPDATE));
        }
        // 根据id获取文章
        Article article = articleMapper.selectByPrimaryKey(id);

        // 校验文章状态
        if(article == null || article.getState() == 1 || article.getDeleteState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }

        // 构建文章修改对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId()); // id
        updateArticle.setReplyCount(article.getReplyCount() + 1); // 回复数

        // 调用DAO修改回复数量
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        // 校验
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public List<Article> selectByUserId(Long id) {
        // 根据用户id获取用户
        User user = userService.selectById(id);
        if(user == null || user.getDeleteState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            // 抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        // 根据用户id查询用户的文章
        List<Article> result = articleMapper.selectByUserId(id);
        log.info("获取用户文章成功, id: " + id);
        return result;
    }
}
